<?php
namespace app\serveruser\logic;

use \app\manage\logic\BaseLogic;

/**
 * 角色组管理的逻辑层
 * @author adv30 <adv30@126.com> 2017年6月5日11:35:17
 */
class RoleGroup extends BaseLogic
{
    protected $name = 'role_group';
    protected $config = 'db_config_user';
    private $roleGroupModel = '\app\serveruser\model\RoleGroup';
    private $roleModel = '\app\serveruser\model\Role';
    // 增加一条角色组记录
    public function add(array $data): array
    {
        $data['status'] = '1';
        try{
            $res = $this->model($this->roleGroupModel)->save($data);
        }catch (\Exception $e) {
            // 当唯一键重复等报错时
            return server_err(null, '数据库异常:' . $e->getMessage());
        }
        return auto_return($res, '成功增加一条角色组记录', '增加一条角色组记录失败');
    }
    // 禁用一个角色组
    public function stop(array $data): array
    {
        isset($data['id']) ? $_where['id'] = $data['id'] : null;
        isset($data['name']) ? $_where['name'] = $data['name'] : null;
        if(!isset($_where)){
            return verify_err(null, '至少要传一个id或name参数');
        }
        $res = $this->model($this->roleGroupModel)->where($_where)->update(['status'=>'0']);
        return auto_return($res, '成功禁用一个角色组', '禁用一个角色组失败');
    }
    // 按分页获取角色组列表
    public function list(array $data): array
    {
        isset($data['status']) ? $_where['status'] = $data['status'] : null;
        if(isset($_where)){
            $list = $this->model($this->roleGroupModel)
                        ->where($_where)
                        ->paginate($data['list_rows'], false, ['page'=>$data['page']])
                        ->toArray();
        }else{
            $list = $this->model($this->roleGroupModel)
                        ->paginate($data['list_rows'], false, ['page'=>$data['page']])
                        ->toArray();  
        }

        return auto_return_page($list, '成功获取角色列表', '获取角色列表失败');
    }
    // 编辑用户角色组信息
    public function edit(array $data): array
    {
        $_where['id'] = $data['id'];
        try{
            $res = $this->model($this->roleGroupModel)
                        ->where($_where)
                        ->update($data);
        }catch (\Exception $e) {
            // 当唯一键重复等报错时
            return server_err(null, '数据库异常:' . $e->getMessage());
        }
        return auto_return($res, '成功编辑角色组信息', '编辑角色组信息失败');
    }
    // 根据role_group_ids解析成角色ids
    public function roleGroupIdsToRoleIds(array $data): array
    {
        $_where['id'] = ['in', $data['group_ids']];
        $_where['status'] = 1;
        $list = $this->db()->where($_where)->column('role_ids');
        if (!$list) { return null_data(null, '没有相关数据'); };
        $ids = '';
        foreach($list as $k => $v){
            $ids .= $v . ',';
        }
        $idsArr = array_unique( explode(',', trim($ids, ',')) );
        $ids = implode(',', $idsArr);
        return auto_return($ids, '成功解析角色组信息', '解析角色组信息失败');
    }
}
